<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div v-show="isShow && menuConfigRef" id="x6-menu-wrap" class="x6-menu-wrap">
    <div class="x6-menu">
      <div v-for="(menu, index) in menuConfigRef" :key="'menu' + index" class="x6-menu-item" @click="buttonClick(menu)">
        <el-divider v-if="(menu as any).divider" />
        <div v-else class="item-text-container">
          <span>
            <svg-icon :icon-class="(menu as any).icon" />
            {{ (menu as any).title }}
          </span>
          <span class="bindKey">{{ (menu as any).bindKey }} </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" >
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from "vue"
import { designerStore } from 'src/stores/designerTool/designerTool'
import { instancesState, instancesStateText } from 'src/utils/designerTool/constants'
import { postRunWorkflows, putRuninfos, putWorkflowStatus, getWorkflowsDetail, getRuninfos } from 'src/api/designerTool'
import Mousetrap from 'mousetrap'
import { algoNodeValidate, secondToTime } from 'src/utils/designerTool/toole'
import dagGraph from 'src/pages/designerTool/canvas/DagEdit/graph/index.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import { number } from "echarts"
const store = designerStore()
const isShow = ref(false)
const menuPosition = ref({ x: null, y: null })
const timingWorkflowRunInfo = ref()
const instancesResults = ref({})
const menuConfigRef = ref([])
const demoTest = ref(<any>[])
const instanceAlgoKey = ref({})
const time = ref(0)
const workflowDag = ref(<any>{})
const versionData = ref(<any>{
  workflow_id: 0,
  instance_id: 0
})

const instanceRunning = computed(() => {
  return store.instanceState === instancesState.Running
})
const isInstance = computed(() => {
  return store.workflowInfo.id && store.instanceId
})
const viewVersion = computed(() => {
  return !!store.versionId
})
const viewExperiment = computed(() => {
  return !!store.experimentId || !!store.flowReadonlyId
})
const readonly = computed(() => {
  return viewVersion.value || viewExperiment.value
})
const isExperiment = computed(() => {
  return store.LeftTabsState == false && store.experiments_id.workflow_id > 0
})
watch(() => store.versionId, (newData, oldData) => {
  initEvent()
  stateFun()
})
watch(() => store.events.initEvent.index, () => {
  initEvent()
})
watch(() => store.events.initInstancesRunInfo.index, () => {
  getInstancesRunInfo()
})
watch(() => store.events.updateRunState.index, () => {
  buttonClick(store.events.updateRunState.data)
})
watch(() => store.events.initEvent.index, () => {
  if (isShow.value && ((new Date().getTime() - time.value) > 100)) {
    menuClose()
  }
})
watch(() => store.workflowWebsocketDag, (newData, oldData) => {
  let sokcetData = JSON.parse(newData)
  let workflow_id = store.workflow_id
  if (isExperiment.value) {
    workflow_id = store.experiments_id.workflow_id
  }
  if (sokcetData.data.workflow_id == workflow_id) {
    getWorkDetails('')
    workflowRunInfoWebsocketState(sokcetData.data)
  }
})
onMounted(() => {
  nextTick(() => {
    initEvent()
    stateFun()
  })
})
// 获取工作流算子状态
function stateFun() {
  getWorkDetails('stateFun')
}
function getWorkDetails(type: string) {
  let workflow_id = store.workflow_id
  if (store.LeftTabsState == false && store.experiments_id.workflow_id > 0) {
    workflow_id = store.experiments_id.workflow_id
  }
  if (typeof store.versionId == 'number' && store.versionId > 0) {
    workflow_id = store.versionId
    versionData.value.workflow_id = store.versionId
  }
  getWorkflowsDetail(store.project_id, workflow_id).then(res => {
    let { ...dag } = JSON.parse(res.data.dag)
    store.SAVE_DAG(dag)
    workflowDag.value = dag
    if (type == 'stateFun') {
      if (typeof store.versionId == 'number' && store.versionId > 0) {
        workflowDag.value.cells.forEach((ele: any, index: number) => {
          if (ele.shape === 'vue-shape' && ele.component === 'algo-node') {
            let config = JSON.stringify(ele.data.configs)
            nodeState(ele.id, config, 'Scheduled')
          }
        })
      } else {
        if (res.data.dag.length > 15) {
          store.SET_INSTANCE_ID(res.data.instance_id)
          let instanceId = store.instanceId
          if (isExperiment.value) { instanceId = store.experiments_id.id }
          if (!!instanceId) {
            getNodeInfos()
          }
        }
      }
    }
  }).catch(error => {
    console.log(error)
  })
}


function initEvent() {
  // 右键 blank 画布空白区域
  dagGraph.graph?.on('blank:contextmenu', (data) => {
    menuShow(data, 'blank')
  })
  // 右键 node 节点
  dagGraph.graph?.on('node:contextmenu', (data) => {
    cleanSelection()
    dagGraph.graph?.select(data.node)
    store.SET_SELECTED_ID(data.node.id)
    menuShow(data, 'node')
  })
  dagGraph.graph?.on('blank:click', () => {
    menuClose()
  })
  dagGraph.graph?.on('cell:click', () => {
    menuClose()
  })
  dagGraph.graph?.on('node:click', () => {
    menuClose()
  })
  dagGraph.graph?.on('edge:click', () => {
    menuClose()
  })
  dagGraph.graph?.on('node:added', () => {
    menuClose()
  })
  dagGraph.graph?.on('node:move', () => {
    menuClose()
  })
  // 删除键
  // Mousetrap.bind('backspace', () => {
  //   this.deleteNode()
  //   return false
  // })
  if (!readonly.value) {
    // 右键 edge 边
    dagGraph.graph?.on('edge:contextmenu', (data) => {
      dagGraph.graph?.resetSelection(data.edge)
      menuShow(data, 'edge')
    })
    dagGraph.graph?.bindKey('delete', () => {
      deleteNode()
    })
    // 算子置于顶层
    Mousetrap.bind('ctrl+]', () => {
      buttonClick({ key: 'toFront' })
      return false
    })
    // 算子置于底层
    Mousetrap.bind('ctrl+[', () => {
      buttonClick({ key: 'toBack' })
      return false
    })
  }
}
function menuShow({ e, cell, view, x, y, node }, menuType) {
  time.value = new Date().getTime()
  let menuConfig = <any>[]
  switch (menuType) {
    case 'blank':
      menuConfig.push(
        {
          title: '打开画布信息',
          icon: 'Hdonghua-xiangzuozhankai',
          key: 'openDrawer',
          bindKey: 'Ctrl+I'
        }
      )
      if (isInstance.value) {
        menuConfig.push({
          title: '查看日志',
          icon: 'rizhi',
          key: 'openWorkflowLog',
          bindKey: 'Ctrl+L'
        })
      }
      if (store.paste) {
        menuConfig.push({
          title: '粘贴',
          icon: 'niantie1',
          key: 'paste',
          bindKey: 'Ctrl+V'
        })
      }
      break
    case 'node': {
      if (!readonly.value) {
        menuConfig.push(
          {
            title: '复制',
            icon: 'copy',
            key: 'copy',
            bindKey: 'Ctrl+C'
          })

        if (store.paste) {
          menuConfig.push({
            title: '粘贴',
            icon: 'niantie1',
            key: 'paste',
            bindKey: 'Ctrl+V'
          })
        }
        menuConfig.push({
          title: '删除',
          icon: 'icon',
          key: 'deleteNode',
          bindKey: 'Delete'
        })

        const nodeEdges = dagGraph.graph?.getConnectedEdges(node)
        if (nodeEdges.length) {
          menuConfig.push({
            title: '断开边连接',
            icon: 'duankai',
            key: 'disconnect'
          })
        }
        menuConfig.push({
          title: '置于顶层',
          icon: 'zhiyudingceng',
          key: 'toFront',
          bindKey: 'Ctrl+]'
        })
        menuConfig.push({
          title: '置于底层',
          icon: 'zhiyudiceng',
          key: 'toBack',
          bindKey: 'Ctrl+['
        })
      }
      const nodeData = node.getData()
      if (!viewExperiment.value) {
        // menuConfig.push({
        //   title: '运行至此',
        //   icon: 'yunhang',
        //   key: 'runChoice'
        // })
        const incomingEdges = dagGraph.graph?.getIncomingEdges(node)
        if (incomingEdges) {
          let isAllSuccessNum = 0
          if (incomingEdges.length) {
            incomingEdges.forEach(row => {
              if (row.getSourceNode() && row.getSourceNode().getData().status === instancesState.Success) {
                isAllSuccessNum++
              }
            })
          }
          if (isAllSuccessNum !== 0 && incomingEdges.length === isAllSuccessNum && instancesResults.value[store.selectedId]) {
            menuConfig.push({
              title: '运行当前节点',
              icon: 'yunhang',
              key: 'restartKernel'
            })
          }
        }
        if (nodeData.status === instancesState.Paused) {
          menuConfig.push({
            title: '继续运行',
            icon: 'yunhang',
            key: 'resumeOperation'
          })
        }
      }
      if (viewExperiment.value || isInstance.value) {
        if (!viewExperiment.value) {
          menuConfig.push({
            divider: true
          })
        }
        menuConfig.push({
          title: '运行日志',
          icon: 'rizhi',
          key: 'openOperatorLog',
          bindKey: 'Ctrl+L'
        })
        menuConfig.push({
          title: '运行结果',
          icon: 'tongjichaifenjieguo',
          key: 'openOperatorResult',
          bindKey: 'Ctrl+G'
        })
        const categoriesData = store.categoriesSubset[nodeData.id]
        if (categoriesData?.storages) {
          const storages = categoriesData.storages
          if (storages.artifact) {
            menuConfig.push({
              title: '文件',
              icon: 'wj-wjhs',
              key: 'openOperatorArtifact',
              bindKey: 'Ctrl+H'
            })
          }
          if (storages.data) {
            menuConfig.push({
              title: '数据',
              icon: 'shujukaifa',
              key: 'openOperatorData',
              bindKey: 'Ctrl+D'
            })
          }
          if (storages.model) {
            menuConfig.push({
              title: '模型',
              icon: 'moxingxunlian',
              key: 'openOperatorModel',
              bindKey: 'Ctrl+M'
            })
          }
        }
      }
      break
    }
    case 'edge':
      if (!readonly.value) {
        menuConfig = [
          {
            title: '删除',
            icon: 'icon',
            key: 'deleteEdge',
            bindKey: 'Delete'
          }
        ]
      }
      break
    default:
  }
  menuConfigRef.value = menuConfig
  demoTest.value = menuConfig
  menuPosition.value.x = x
  menuPosition.value.y = y
  const point: any = dagGraph.graph?.localToPage({ x, y })
  const elem: any = document.querySelector('.x6-menu-wrap')
  let addTopDistance = menuConfigRef.value.length * 32
  const x6Graph: any = document.querySelector('.x6-graph-box')
  if ((point.y + addTopDistance) < (x6Graph.clientHeight + 70)) {
    addTopDistance = 0
  }
  elem.style.top = (point.y - addTopDistance) + 'px'
  elem.style.left = (point.x + 10) + 'px'
  isShow.value = true
}
function graphPointToOffsetPoint(graphPoint: any) {
  if (dagGraph.graph) {
    const point = dagGraph.graph?.localToPage({ x: graphPoint.offsetX, y: graphPoint.offsetY })
    const clientRect = document.getElementById('x6-graph-container')?.getBoundingClientRect()
    const y = point.y - (clientRect?.y || 0) // ! offset parent 不能是画布容器，否则会影响内部布局，所以 offset parent 在外部，算上上方 toolbar 的高度
    const x = point.x - (clientRect?.x || 0)
    return { x, y }
  }
  return { x: 0, y: 0 }
}
function menuClose() {
  isShow.value = false
  menuConfigRef.value = []
  menuPosition.value.x = null
  menuPosition.value.y = null
}
function deleteNode() {
  const cell: any = dagGraph.graph?.getSelectedCells()
  if (cell.length) {
    if (cell.length === 1 && cell[0].shape === 'edge') {
      dagGraph.graph?.removeEdge(cell[0])
    } else {
      const algoNum = cell.filter((item: any) => item.shape === 'vue-shape' && item.component === 'algo-node').length
      const textNum = cell.filter((item: any) => item.shape === 'vue-shape' && item.component === 'text-node').length
      const groupNum = cell.filter((item: any) => item.shape === 'vue-shape' && item.component === 'algo-group').length
      let message = ''
      let title = ''
      if (algoNum) {
        message = `此操作将删除${algoNum === 1 ? '该' : (algoNum + '个')}算子, 是否继续?`
        title = '删除算子'
      } else if (textNum) {
        message = `此操作将删除文本框, 是否继续?`
        title = '删除文本框'
      } else if (groupNum) {
        message = `此操作将删除组合, 是否继续?`
        title = '删除组合'
      }
      if (title) {
        ElMessageBox.confirm(message, title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          cell.forEach((row: any) => {
            const parent = row.getParent()
            dagGraph.removeCell(row.id)
            if (parent && parent.getDescendants().length === 0) {
              dagGraph.removeCell(parent.id)
            }
          })
          // if (menuClose) {
          //   menuClose()
          // }
        })
      }
    }
  }
}
function buttonClick(menu: any) {
  const { key } = menu
  switch (key) {
    case 'textBox':
      dagGraph.graph?.addNode({
        x: menuPosition.value.x,
        y: menuPosition.value.y,
        shape: 'vue-shape',
        component: 'text-node',
        data: {
          value: '文本框',
          edit: 'close'
        }
      })

      break
    case 'copy':
      dagGraph.copyNode()
      break
    case 'paste': {
      dagGraph.pasteNode(menuPosition.value.x, menuPosition.value.y)
      break
    }
    case 'runModule': {
      runModule(null)
      break
    }
    case 'deleteNode':
    case 'deleteEdge':
      deleteNode()
      break
    case 'combination': {
      // this.combination()
      break
    }
    case 'ungroup':
      break
    case 'disconnect':
      disconnectFunc()
      break
    case 'runChoice':
      runChoice()
      break
    case 'restartKernel':
      restartKernel()
      break
    case 'resumeOperation':
      resumeOperation()
      break
    case 'toFront': {
      const cell: any = dagGraph.graph?.getSelectedCells()
      cell.forEach((row: any) => {
        row.toFront()
      })
      break
    }
    case 'toBack': {
      const cell: any = dagGraph.graph?.getSelectedCells()
      cell.forEach((row: any) => {
        row.toBack()
      })
      break
    }
    case 'workflowScheduled': {
      updateWorkflowState('Reloading')
      break
    }
    case 'workflowPaused': {
      updateWorkflowState(instancesState.Paused)
      break
    }
    case 'workflowResume': {
      updateWorkflowState('Resume')
      break
    }
    case 'workflowCancelled': {
      updateWorkflowState('Cancelled')
      break
    }
    case 'openDrawer': {
      cleanSelection()
      store.SET_RIGHT_DRAWER(true)
      break
    }
    case 'openWorkflowLog': {
      cleanSelection()
      store.SET_RIGHT_DRAWER_TAB_TYPE('workflowLog')
      break
    }
    case 'openOperatorLog': {
      store.SET_RIGHT_DRAWER_TAB_TYPE('runLog')
      break
    }
    case 'openOperatorResult': {
      store.SET_RIGHT_DRAWER_TAB_TYPE('runResult')
      break
    }
    case 'openOperatorArtifact': {
      store.SET_RIGHT_DRAWER_TAB_TYPE('artifact')
      break
    }
    case 'openOperatorData': {
      store.SET_RIGHT_DRAWER_TAB_TYPE('data')
      break
    }
    case 'openOperatorModel': {
      store.SET_RIGHT_DRAWER_TAB_TYPE('model')
      break
    }
    default:
  }
  menuClose()
}
function runChoice() {
  if (store.selectedId) {
    const node: any = dagGraph.graph?.getCellById(store.selectedId)
    const nodeData = node.getData()
    runModule({
      pause_node_id: store.selectedId,
      pause_operator_id: nodeData.id
    })
  }
}
function runModule(formData: any) {
  instanceAlgoKey.value = {}
  cleanSelection()
  const nodes: any = dagGraph.graph?.getNodes()
  if (nodes.length) {
    if (isInstanceRunning()) return
    if (viewVersion.value) {
      workflowRun(formData)
    } else {
      store.SET_INSTANCE_STATE(instancesState.Running)
      store.SET_INSTANCES_RUN_DATA({})
      setNodePendingState()
      getWorkflowRunInfo()
      dagGraph.saveOrUpdateWorkflowData().then(res => {
        workflowRun(formData)
      }, res => {
        store.SET_INSTANCE_STATE(instancesState.Failed)
        ElMessage.error('工作流保存错误')
      })
    }
  } else {
    ElMessage.warning('请添加一个算子')
  }
  if (store.selectedId) {
    const node: any = dagGraph.graph?.getCellById(store.selectedId)
    const nodeData = node.getData()
    runModule({
      pause_node_id: store.selectedId,
      pause_operator_id: nodeData.id
    })
  }
}
function workflowRun(formData: any) {
  let errorType = ''
  const nodes: any = dagGraph.graph?.getNodes()
  for (let i = 0; i < nodes.length; i++) {
    errorType = algoNodeValidate(nodes[i])
    if (errorType) {
      break
    }
  }
  if (errorType) {
    let errorMessage = '请检查算子中参数必填项.'
    if (errorType === 'connect') {
      errorMessage = '请确保算子节点中输入节点全部有算子连接.'
    }
    ElMessage.warning(errorMessage)
    store.SET_INSTANCE_STATE('')
    return
  }
  store.SET_INSTANCE_STATE(instancesState.Running)
  store.SET_INSTANCES_RUN_DATA({})
  postRunWorkflows(store.project_id, store.workflow_id).then(res => {
    store.SET_INSTANCE_ID(res.data.id)
    getInstancesRunInfo()
  }, res => {
    store.SET_INSTANCE_STATE(instancesState.Failed)
  })
}

const runningSate = ref(false)
function getInstancesRunInfo() {
  runningSate.value = false
  const nodes: any = dagGraph.graph?.getNodes()
  const nodeIndex: any = {}
  nodes.forEach((row: any, index: number) => {
    nodeIndex[row.id] = index
  })
  instanceAlgoKey.value = nodeIndex
  getWorkflowRunInfo()
  // runTime()

}
function runTime() {
  let timestamp = Date.now()
  let dateObj = {
    start_ts: Math.round(timestamp / 1000)
  }
  let checkState = setInterval(() => {
    if (store.instancesRunData.state != 'running') {
      clearInterval(checkState)
    } else {
      store.instancesRunData.run_time = secondToTime(dateObj)
    }
  }, 1000)
}

// 工作流运行
function getWorkflowRunInfo() {
  if (!store.workflowInfo || !store.workflowInfo.id || !store.instanceId) return
  getNodeInfos()
}
// 获取工作流状态
function getNodeInfos() {
  let instanceId = store.instanceId
  let workflow_id = store.workflow_id
  if (isExperiment.value) {
    instanceId = store.experiments_id.id
    workflow_id = store.experiments_id.workflow_id
  }
  putRuninfos(store.project_id, workflow_id, instanceId).then(res => {
    workflowRunInfoWebsocketState(res.data)
  }, (res: any) => {
    ElMessage(res.result)
  })
}

// 画布数据赋值
function workflowRunInfoWebsocketState(resData: any) {

  store.SET_ALL_OPERATOR(resData.operator_instances)
  let dateObj: any = {
    start_time: Date.parse(resData.start_time) / 1000
  }
  if (resData.finish_time != null) {
    dateObj.end_time = Date.parse(resData.finish_time) / 1000
  }
  if (resData.status != 'running') { runningSate.value = true }
  let instanceState = resData.status
  store.SET_INSTANCES_RUN_DATA({
    start_time: resData.start_time,
    end_time: resData.finish_time,
    // run_time: secondToTime(dateObj),
    state: resData.status,
    message: ''
  })
  switch (resData.status) {
    case instancesState.Scheduled:
      instanceState = instancesState.Running
      break
    default:
  }
  let isRunning = false
  resData.operator_instances.forEach((row: any) => {
    let statusString = ''
    let rowStatus = row.status.replace(/( |^)[a-z]/g, (L: any) => L.toUpperCase())  //首字母大写
    switch (rowStatus) {
      case instancesState.Scheduled:
        statusString = instancesState.Pending
        break
      case instancesState.Pending:
      case instancesState.Success:
      case instancesState.Running:
      case instancesState.Paused:
      case instancesState.Cancelled:
        statusString = row.status
        break
      case instancesState.Resume:
      case instancesState.Submitted:
        statusString = instancesState.Running
        isRunning = true
        break
      default:
        statusString = instancesState.Failed
    }
    // nodeState(row.node_id, row.configs, statusString)
    setTimeout(() => {
      workflowDag.value.cells.forEach((ele: any, index: number) => {
        const nodeById: any = dagGraph.graph?.getCellById(ele.id)
        if (ele.shape === 'vue-shape' && ele.component === 'algo-node') {
          if (row.node_id == ele.id) {
            row.configs = JSON.stringify(ele.data.configs)
          }
          if (row.node_id != ele.id && nodeById.data.status == 'Scheduled') {
            let config = JSON.stringify(ele.data.configs)
            nodeState(ele.id, config, 'Scheduled')
          }
        }
      })
      nodeState(row.node_id, row.configs, statusString)
    }, 500)
  })
  if (instanceState !== instancesState.Running) {
    // getInstancesResults()
    // 暂停之后如果有运行中的就继续执行
    if ((store.instanceState === instancesState.Running && instanceState === instancesState.Paused) || (instanceState === instancesState.Paused && isRunning)) {
      workflowRunInfoTimeout()
    }
  } else {
    workflowRunInfoTimeout()
  }
  instanceState = resData.status.replace(/( |^)[a-z]/g, (L: any) => L.toUpperCase())
  store.SET_INSTANCE_STATE(instanceState)
}
function nodeState(nodeId: string, config: any, state: string) {
  const nodeById: any = dagGraph.graph?.getCellById(nodeId)
  if (nodeById) {
    const data = nodeById.getData()
    data.configs = JSON.parse(config)
    data.configs.forEach((ele: any) => {
      if (ele.param_type == 'common' || ele.param_type == 'input') {
        if (ele.value != undefined) {
          data[ele.name] = ele.value
        }
      }
    })
    nodeById.setData({
      ...data,
      status: state,
    })
  }
}

// function getInstancesResults() {
//   this.$api.getWorkflowInstancesResults(store.workflowInfo.id, store.instanceId).then(res => {
//     instancesResults.value = res.result
//   }, (res: any) => {
//     ElMessage(res.result)
//   })
// }
function workflowRunInfoTimeout() {
  timingWorkflowRunInfo.value = setTimeout(() => {
    getWorkflowRunInfo()
  }, 1000)
}
function setNodePendingState() {
  const nodes: any = dagGraph.graph?.getNodes()
  nodes.forEach((row: any) => {
    const data = row.getData()
    row.setData({
      ...data,
      status: instancesState.Pending
    })
  })
}
// function getGroupConfig(cells, embedPadding = 20, titleHeight = 10) {
//   let parentTopX = null
//   let parentTopY = null
//   let parentBottomX = null
//   let parentBottomY = null
//   cells.forEach(cell => {
//     const nodeData = cell.store.data
//     if (parentTopX === null || nodeData.position.x < parentTopX) {
//       parentTopX = nodeData.position.x
//     }
//     if (parentTopY === null || nodeData.position.y < parentTopY) {
//       parentTopY = nodeData.position.y
//     }

//     if (parentBottomX === null || (nodeData.position.x + nodeData.size.width) > parentBottomX) {
//       parentBottomX = nodeData.position.x + nodeData.size.width
//     }
//     if (parentBottomY === null || (nodeData.position.y + nodeData.size.height) > parentBottomY) {
//       parentBottomY = nodeData.position.y + nodeData.size.height
//     }
//   })
//   return {
//     x: parentTopX - embedPadding,
//     y: parentTopY - embedPadding - titleHeight,
//     width: Math.abs(parentTopX - parentBottomX) + embedPadding * 2,
//     height: Math.abs(parentTopY - parentBottomY) + embedPadding * 2 + titleHeight
//   }
// }
function combination() {
  const cells: any = dagGraph.graph?.getSelectedCells()
  if (cells.length) {
    // const algoNodeList = cells.filter(item => item.shape === 'vue-shape' && item.component === 'algo-node')
    // const idList = algoNodeList.map(row => row.id)
  } else {
    ElMessage.warning('请选择一个算子')

  }
}
function groupOn() {
  // let ctrlPressed = false
  //
  // dagGraph.graph.on('node:embedding', ({ e }) => {
  //   ctrlPressed = e.metaKey || e.ctrlKey
  // })
  //
  // dagGraph.graph.on('node:embedded', () => {
  //   ctrlPressed = false
  // })
  //
  // dagGraph.graph.on('node:change:size', ({ node, options }) => {
  //   if (options.skipParentHandler) {
  //     return
  //   }
  //
  //   const children = node.getChildren()
  //   if (children && children.length) {
  //     node.prop('originSize', node.getSize())
  //   }
  // })
  //
  // dagGraph.graph.on('node:change:position', ({ node, options }) => {
  //   if (options.skipParentHandler || ctrlPressed) {
  //     return
  //   }
  //   const parent = node.getParent()
  //   if (parent) {
  //     const children = parent.getChildren()
  //     if (children && children.length) {
  //       const { x, y, width, height } = this.getGroupConfig(children)
  //       parent.prop({ position: { x, y }, size: { width, height }}, { skipParentHandler: true })
  //     }
  //   }
  // })
}
function disconnectFunc() {
  if (store.selectedId) {
    const node: any = dagGraph.graph?.getCellById(store.selectedId)
    dagGraph.graph?.removeConnectedEdges(node)
  }
}
function cleanSelection() {
  dagGraph.graph?.cleanSelection()
  store.SET_SELECTED_ID('')
}
function isInstanceRunning() {
  if (instanceRunning.value) {
    ElMessage.error(`正在${instancesStateText.Running}...请等待运行结束`)
  }
  return instanceRunning.value
}
function resumeOperation() {
  if (isInstanceRunning()) return
  // if (store.selectedId) {
  //   const resDatum = instancesResults.value[this.selectedId]
  //   this.$api.updateInstancesStates(resDatum.id, {
  //     state: instancesState.Resume
  //   }).then(res => {
  //     if (!instanceRunning.value) {
  //       getInstancesRunInfo()
  //     }
  //   }, res => {
  //     ElMessage(res.result)
  //   })
  // }
}
function restartKernel() {
  if (isInstanceRunning()) return
  // if (store.selectedId) {
  //   const resDatum = this.instancesResults[this.selectedId]
  //   this.$api.updateInstancesStates(resDatum.id, {
  //     state: instancesState.Run
  //   }).then(res => {
  //     if (!instanceRunning.value) {
  //       getInstancesRunInfo()
  //     }
  //     ElMessage(res.result)
  //   })
  // }
}
function updateWorkflowState(state: string) {
  let statusStr = ''
  switch (state) {
    case 'Reloading':
      statusStr = 'reload'
      break
    case 'Resume': {
      if (isInstanceRunning()) return
      statusStr = 'resume'
      break
    }
    case 'Paused': {
      if (!instanceRunning.value) {
        ElMessage.error('请先运行')
        return
      }
      statusStr = 'paused'
      break
    }
    case 'Cancelled':
      statusStr = 'canceled'
      break
    default:
  }
  if (!store.instanceId) {
    ElMessage('服务正在启动中,请稍后操作')
    return
  }
  // 暂停
  changeWorkflowState(statusStr)
}
function changeWorkflowState(str: string) {
  putWorkflowStatus(store.project_id, store.workflow_id, store.instanceId, { status: str }).then(res => {
    getInstancesRunInfo()
    // if (!instanceRunning.value) {
    //   getInstancesRunInfo()
    // }
  }).catch(error => {
    console.log(error)
  })
}

</script>

<style lang="scss" scoped>
@import "src/css/designerStyles/index.scss";
$back-ground-color: #fff;

.x6-menu-wrap {
  position: absolute;
  z-index: 9999;
  box-shadow: 0 0 10px 0 #d6d6d6;

  .x6-menu {
    position: relative;
    display: inline-block;
    min-width: 160px;
    min-height: 32px;
    margin: 0;
    padding: 4px 0;
    background-color: $back-ground-color;
    outline: 0;
    cursor: pointer;

    .x6-menu-item {
      white-space: nowrap;
      padding: 0 10px;
      font-size: 14px;
      line-height: 32px;

      .svg-icon {
        margin-right: 4px;
        fill: #4a4a4a;
      }

      &:hover {
        color: #0080ff;
        background: #F8FAFB;

        .svg-icon {
          fill: #0080ff;
        }
      }

      .el-divider {
        margin: 0;
      }

      .item-text-container {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .bindKey {
          color: #777;
          margin-left: 10px;
        }
      }
    }
  }
}

::v-deep .x6-menu {
  .el-button {
    width: 100%;
    border: none;
    text-align: left;

    &:hover {
      color: #0080ff;
      background: #F8FAFB
    }
  }
}
</style>
